<template>
	<view class="step-item">
		<!-- 步骤头部 -->
		<view class="step-header">
			<view class="step-icon">⚙️</view>
			<view class="step-title-main">发布设置</view>
			<view class="step-description">设置报名套餐、收益比例和优惠券等发布相关配置</view>
		</view>

		<view class="activity-title">
			<text class="title-text">{{ activityData.name || '活动名称' }}</text>
			<text class="fee-note">注：活动上架费5元</text>
		</view>

		<!-- 报名套餐设置 -->
		<view class="section">
			<view class="section-title">报名套餐设置</view>
			<!-- <u-loading mode="circle" v-if="!activitySpecs.spec_value_list" /> -->
			<view class="package-list">
				<view v-if="activitySpecs && activitySpecs.spec_value_list && activitySpecs.spec_value_list.length > 0">
					<view 
						class="package-item" 
						v-for="(spec, index) in activitySpecs.spec_value_list" 
						:key="index"
						v-if="spec && spec.spec_value_str"
					>
						<view class="package-content">
							<text class="requirement">人员要求：{{ formatSpecValues(spec.spec_value_str) }}</text>
							<view class="price-info">
								<text class="original-price">¥{{ spec.original_price || 0 }}</text>
								<text class="current-price">¥{{ spec.price || 0 }}</text>
								<text class="discount" v-if="spec.original_price && spec.price && parseFloat(spec.original_price) > 0">({{
									Math.round((parseFloat(spec.price) / parseFloat(spec.original_price)) * 100) / 10
								}}折)</text>
								<!-- <text class="stock">库存：{{ spec.stock }}</text> -->
							</view>
						</view>
					</view>
				</view>
				<view v-else class="empty-tips">暂无套餐数据</view>
			</view>
			<view class="add-package" @click="addPackage">
				<u-icon name="plus" size="20" color="#0DC160"></u-icon>
				<text>添加/编辑报名套餐</text>
			</view>
		</view>

		<!-- 收益比例设置 -->
		<view class="section">
			<view class="section-title">收益比例设置</view>
			<view class="profit-settings">
				
				<view class="setting-group">
					<view class="sub-title">分享人设置</view>
					<view class="radio-group">
						<radio-group @change="setShareType">
							<label class="radio-item horizontal">
								<radio value="1" :checked="shareType === 1" /> 比例（%）
							</label>
							<label class="radio-item horizontal">
								<radio value="2" :checked="shareType === 2" /> 固定金额（元）
							</label>
						</radio-group>
					</view>
					<view class="input-group">
						<input 
							v-if="shareType === 1"
							type="number" 
							placeholder="分享人比例" 
							v-model="shareRatio"
							@input="saveToCache"
						/>
						<input 
							v-else
							type="number" 
							placeholder="分享人固定金额" 
							v-model="shareFixed"
							@input="saveToCache"
						/>
						<text class="unit">{{ shareType === 1 ? '%' : '元' }}</text>
					</view>
				</view>

				
				<!-- <view class="setting-group">
					<view class="sub-title">陪伴师设置</view>
					<view class="radio-group">
						<radio-group @change="setImplementType">
							<label class="radio-item horizontal">
								<radio value="1" :checked="implementType === 1" /> 比例（%）
							</label>
							<label class="radio-item horizontal">
								<radio value="2" :checked="implementType === 2" /> 固定金额（元）
							</label>
						</radio-group>
					</view>
					<view class="input-group">
						<input 
							v-if="implementType === 1"
							type="number" 
							placeholder="陪伴师比例" 
							v-model="implementRatio"
						/>
						<input 
							v-else
							type="number" 
							placeholder="陪伴师固定金额" 
							v-model="implementFixed"
						/>
						<text class="unit">{{ implementType === 1 ? '%' : '元' }}</text>
					</view>
				</view> -->
			</view>
		</view>

		<!-- 收益计算结果 -->
		<view class="section">
			<view class="section-title">收益计算结果</view>
			<view class="income-result" v-if="minProfit && maxProfit">
				<text>最低收益：¥{{ minProfit || 0 }} - 最高收益：¥{{ maxProfit || 0 }}</text>
			</view>
			<view v-else-if="!loading" class="income-tips">
				<text>请先完成收益比例设置</text>
			</view>
			<view class="loading-wrapper" v-if="loading">
				<u-loading mode="circle" color="#0DC160"></u-loading>
				<text class="loading-text">正在计算收益...</text>
			</view>
		</view>

		<!-- 优惠券设置 -->
		<view class="section">
			<view class="section-title">优惠券设置</view>
			<view class="coupon-settings">
				<view class="coupon-item">
					<u-checkbox class="enable-coupon" v-model="isCouponEnabled" active-color="#0DC160">
						<text>启用优惠券</text>
					</u-checkbox>
				</view>
				<view class="coupon-item">
					<input 
						type="number" 
						placeholder="请输入优惠金额" 
						placeholder-class="placeholder" 
						:disabled="!isCouponEnabled" 
						v-model="couponAmount"
						@input="saveToCache" 
					/>
					<text class="unit">元</text>
				</view>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="bottom-buttons">
			<view class="cancel-btn" @click="prevStep">
				<text>上一步</text>
			</view>
			<view class="save-btn" @click="submit">
				<text>提交审核</text>
			</view>
		</view>

		<!-- 点击添加/编辑报名套餐 -->
		<u-popup v-model="showPopup" mode="bottom" :closeable="true">
			<view class="popup-container">
				<view class="popup-header">
					<view class="popup-wrapper">
						<text class="popup-title">添加报名套餐规格</text>
					</view>

					<!--          <view class="close-icon" @click="showPopup = false">
            <u-icon name="close" size="20"></u-icon>
          </view> -->
				</view>

				<view class="popup-content">
					<!-- 规格设置 -->
					<view class="spec-section">
						<view class="section-header">
							<text>规格设置</text>
							<text class="limit-text">(限制最多3个规格)</text>
							<view class="add-spec" @click="addSpecItem">
								<text>+添加规格项</text>
								<!-- <u-icon name="plus" color="#0DC160" size="14"></u-icon> -->
							</view>
						</view>

						<view class="spec-list">
							<view class="spec-item" v-for="(item, index) in specList" :key="index">
								<view class="spec-name-section">
									<view class="spec-name-header">
										<text>规格名称</text>
										<image src="/static/images/htqrdel.png" mode="" style="width: 26rpx; height: 24rpx" @click="deleteSpec(index)"></image>
									</view>
									<input type="text" class="spec-name-input" placeholder="请输入" v-model="item.name" />
								</view>
								
								<view class="spec-values-section">
									<view class="spec-values-header">
										<text>规格值</text>
										<view class="add-value" @click="addSpecValue(index)">
											<text>+添加</text>
										</view>
									</view>
									<view class="value-list">
										<view class="value-item" v-for="(value, vIndex) in item.spec_list" :key="vIndex">
											<input type="text" placeholder="请输入" v-model="value.value" />
											<image src="/static/images/htqrdel.png" mode="" style="width: 26rpx; height: 24rpx" @click="deleteValue(index, vIndex)"></image>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>

					<!-- 报名套餐价格设置 -->
					<view class="price-section">
						<view class="section-header">
							<text>报名套餐价格设置</text>
						</view>
						<view class="price-table">
							<view class="table-header">
								<text>规格名</text>
								<text>原价</text>
								<text>售价</text>
							</view>
							<view class="table-row" v-for="(spec, index) in priceList" :key="index">
								<text class="spec-name">{{ spec.spec_value_str }}</text>
								<input type="number" placeholder="请输入" v-model="spec.original_price" />
								<input type="number" placeholder="请输入" v-model="spec.price" />
							</view>
						</view>
					</view>
				</view>

				<view class="popup-footer">
					<button class="confirm-btn" @click="confirmSpecs">确认</button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import { publishActivity, activityIncome, trainerList } from '@/api/launchevent'
import { mapState } from 'vuex'
import store from 'store'
export default {
	props: {
		activityId: Number,
		activityState: Number,
		activityData: {
			type: Object,
			default: () => ({})
		},
		formCache: {
			type: Object,
			default: () => ({})
		}
	},
	data() {
		return {
			showPopup: false,
			packages: [1, 2], // 示例套餐数据
			shareType: 1, // 1-比例 2-固定金额
			implementType: 1, // 1-比例 2-固定金额
			shareRatio: '', // 分享人比例值
			shareFixed: '', // 分享人固定金额
			implementRatio: '', // 陪伴师比例值
			implementFixed: '', // 陪伴师固定金额
			isCouponEnabled: false, // 新增数据属性，用于记录优惠券是否启用
			couponAmount: '', // 优惠券金额
			// 新增数据
			specList: [], // 规格列表
			priceList: [], // 价格设置列表
			loading: false,
			minProfit: null,
			maxProfit: null,
			trainerId: '',
			activitySpecs: {
				spec_value_list: [] // 确保有默认值
			},
			isLoadingFromCache: false
		};
	},
	computed: {
		...mapState({
			
		}),
		allSettings() {
			return {
				shareType: this.shareType,
				shareRatio: this.shareRatio,
				shareFixed: this.shareFixed,
				implementType: this.implementType,
				implementRatio: this.implementRatio,
				implementFixed: this.implementFixed
			}
		}
	},
	watch: {
		allSettings: {
			handler() {
				this.debouncedCalculateIncome();
				this.saveToCache(); // 实时保存缓存
			},
			deep: true,
			immediate: false
		},
		specList: {
			handler() {
				if (!this.isLoadingFromCache) {
					this.setPriceList();
					this.saveToCache(); // 实时保存缓存
				}
			},
			deep: true,
			immediate: true
		},
		priceList: {
			handler(newVal) {
				if (!this.isLoadingFromCache) {
					console.log(1111111111111,newVal)
					// 避免循环引用，只在数据真正变化时更新
					if (JSON.stringify(this.activitySpecs.spec_value_list) !== JSON.stringify(newVal)) {
						this.activitySpecs.spec_value_list = JSON.parse(JSON.stringify(newVal));
					}
					this.saveToCache(); // 实时保存缓存
				}
			},
			deep: true
		},
		activitySpecs: {
			handler(newVal) {
				if (!this.isLoadingFromCache) {
					console.log(2222222222,newVal)
					// 避免循环引用，只在数据真正变化时更新
					if (newVal && newVal.spec_value_list && JSON.stringify(this.priceList) !== JSON.stringify(newVal.spec_value_list)) {
						this.priceList = JSON.parse(JSON.stringify(newVal.spec_value_list));
					}
				}
			},
			deep: true
		},
		isCouponEnabled: {
			handler() {
				if (!this.isLoadingFromCache) {
					this.saveToCache(); // 实时保存缓存
				}
			}
		},
		couponAmount: {
			handler() {
				if (!this.isLoadingFromCache) {
					this.saveToCache(); // 实时保存缓存
				}
			}
		},
		formCache: {
			handler(newVal) {
				if (newVal && Object.keys(newVal).length > 0) {
					this.loadFromCache();
				}
			},
			deep: true,
			immediate: true
		}
	},
	methods: {
		setPriceList(){
			const { priceList, specList } = this
			console.log(priceList, specList, '#####')

			const inSpecList = specList.map((item) => item.spec_list)
			const newData = this.getTableData(inSpecList)
			console.log(newData, '******')

			const rawData = JSON.parse(JSON.stringify(priceList))
			console.log(rawData, '0000000')

			const rawObject = {}
			rawData.forEach((item) => {
					if (item.spec_value_str !== undefined) {
							rawObject[item.spec_value_str] = item
					}
			})
			console.log(rawObject, '9999999')

			this.priceList = newData.map((item) =>
					rawObject[item.spec_value_str]
							? {
										...rawObject[item.spec_value_str],
										value: item.value,
										ids: item.ids
								}
							: item
			)
		},
		getTableData(arr) {
				arr = JSON.parse(JSON.stringify(arr))
				return arr.reduce(
						(prev, next) => {
								const newArr = []
								for (let i = 0; i < prev.length; i++) {
										if (!next.length) {
												newArr.push(this.setFields(prev[i], {}))
										}
										for (let j = 0; j < next.length; j++) {
												next[j].ids = j
												newArr.push(this.setFields(prev[i], next[j]))
										}
								}
								return newArr
						},
						[{}]
				)
		},
		setFields(prev, next) {
			let valueArr = [prev, next]
			valueArr = valueArr.filter(item => item.value !== undefined)
			const ids = this.flatten(valueArr.map(item => item.ids)).join()
			const value = this.flatten(valueArr.map(item => item.value))
			return {
					id: prev.id ? prev.id : '',
					ids: ids,
					value,
					spec_value_str: value.join(),
					price: prev.price ? prev.price : '',
					original_price: prev.original_price ? prev.original_price : '',
					stock: prev.stock ? prev.stock : '',
				}
		},
		flatten(arr) {
		    return arr.reduce((result, item) => {
		        return result.concat(Array.isArray(item) ? this.flatten(item) : item)
		    }, [])
		},
		debouncedCalculateIncome() {
			clearTimeout(this.debounceTimer);
			this.debounceTimer = setTimeout(() => {
				this.calculateIncome();
			}, 1000); // 输入停止1秒后执行
		},
		addPackage() {
			this.showPopup = true;
		},
		setShareType(e) {
			this.shareType = Number(e.detail.value)
		},
		setImplementType(e) {
			this.implementType = Number(e.detail.value)
		},
		async calculateIncome() {
			if (!this.activityId) return;
			
			const shareValid = this.shareType === 1 
				? !!this.shareRatio && this.shareRatio > 0 
				: !!this.shareFixed && this.shareFixed > 0;
			
			const implementValid = this.implementType === 1 
				? !!this.implementRatio && this.implementRatio > 0 
				: !!this.implementFixed && this.implementFixed > 0;

			if (!shareValid || !implementValid) {
				this.minProfit = null;
				this.maxProfit = null;
				return;
			}

			const params = {
				id: this.activityId,
				share_type: this.shareType,
				implement_type: this.implementType,
				share_rate: this.shareType === 1 ? this.shareRatio : undefined,
				share_money: this.shareType === 2 ? this.shareFixed : undefined,
				implement_rate: this.implementType === 1 ? this.implementRatio : undefined,
				implement_money: this.implementType === 2 ? this.implementFixed : undefined,
				spec_value: this.specList,
				spec_value_list: this.activitySpecs.spec_value_list
			}
			// 过滤未定义的参数
			const filteredParams = Object.fromEntries(
				Object.entries(params).filter(([_, v]) => v !== undefined)
			);

			try {
				this.loading = true;
				const res = await activityIncome(filteredParams);
				
				
					this.minProfit = res.min_profit;
					this.maxProfit = res.max_profit;
				
			} catch (e) {
				uni.showToast({ title: '收益计算失败', icon: 'none' });
			} finally {
				this.loading = false;
			}
		},
		async trainerList() {
			try {
				const res = await trainerList();
				console.log('trainerList API响应:', res);
				
				// 修复API响应结构处理
				let trainerData = null;
				if (res && res.data && res.data.lists && Array.isArray(res.data.lists) && res.data.lists.length > 0) {
					trainerData = res.data.lists;
				} else if (res && res.data && res.data.data && Array.isArray(res.data.data) && res.data.data.length > 0) {
					trainerData = res.data.data;
				} else if (res && res.lists && Array.isArray(res.lists) && res.lists.length > 0) {
					trainerData = res.lists;
				} else if (res && res.data && Array.isArray(res.data) && res.data.length > 0) {
					trainerData = res.data;
				}
				
				if (trainerData && trainerData.length > 0) {
					this.trainerId = trainerData[0].id;
					console.log('获取到的训练师 id:', this.trainerId);
				} else {
					console.log('未找到有效的训练师数据，API响应结构:', res);
				}
			} catch (error) {
				console.error('获取训练师列表失败:', error);
			}
		},
		async submit() {
			// 验证所有必填字段
			if (!this.validateForm()) {
				return;
			}

			// 在提交时增加参数
			const params = {
				id: this.activityId,
				terminal: this.$store.state.app.client,
				share_type: this.shareType,
				implement_type: this.implementType,
				share_rate: this.shareType === 1 ? this.shareRatio : undefined,
				share_money: this.shareType === 2 ? this.shareFixed : undefined,
				implement_rate: this.implementType === 1 ? this.implementRatio : undefined,
				implement_money: this.implementType === 2 ? this.implementFixed : undefined,
				coach_id: this.trainerId,
				spec_value: this.specList,
				spec_value_list: this.activitySpecs.spec_value_list,
				whether_coupon: this.isCouponEnabled ? 1 : 0,
				coupon_money: this.isCouponEnabled ? this.couponAmount : undefined
			}

			// 过滤并提交
			const filteredParams = Object.fromEntries(
				Object.entries(params).filter(([_, v]) => v !== undefined)
			);

			try {
				// 保存当前表单数据
				this.saveToCache();
				
				// 更新活动数据
				const updateData = {
					share_type: this.shareType,
					share_ratio: this.shareRatio,
					share_fixed: this.shareFixed,
					implement_type: this.implementType,
					implement_ratio: this.implementRatio,
					implement_fixed: this.implementFixed,
					spec_list: this.specList,
					activity_specs: this.activitySpecs,
					whether_coupon: this.isCouponEnabled ? 1 : 0,
					coupon_money: this.couponAmount
				};
				this.$emit('updateData', updateData);

				// 提交审核
				publishActivity(filteredParams).then(result => {
					console.log('publish result:', result);
					
					// 如果有订单需要支付，跳转到支付页面
					if (result.order_id) {
						this.$Router.push({
							path: `/pages/payment/payment`,
							query: {
								from: 'order',
								order_id: result.order_id
							}
						});
						return;
					}
					
					// 更新活动状态为审核中
					this.$emit('updateData', { state: 1 });
					// 进入下一步（审核状态页面）
					this.$emit('next');
				}).catch(error => {
					console.error('提交失败:', error);
					uni.showToast({
						title: error.message || '提交失败，请重试',
						icon: 'none',
						duration: 2000
					});
				});
			} catch (e) {
				console.error('提交失败:', e);
				uni.showToast({
					title: '提交失败，请重试',
					icon: 'none',
					duration: 2000
				});
			}
		},
		// 表单验证
		validateForm() {
			// 验证分享人设置
			if (this.shareType === 1) {
				if (!this.shareRatio) {
					uni.showToast({
						title: '请输入分享人比例',
						icon: 'none'
					});
					return false;
				}
				const shareRatioNum = parseFloat(this.shareRatio);
				if (isNaN(shareRatioNum) || shareRatioNum <= 0 || shareRatioNum > 100) {
					uni.showToast({
						title: '分享人比例需在1-100之间',
						icon: 'none'
					});
					return false;
				}
			} else if (this.shareType === 2) {
				if (!this.shareFixed) {
					uni.showToast({
						title: '请输入分享人固定金额',
						icon: 'none'
					});
					return false;
				}
				const shareFixedNum = parseFloat(this.shareFixed);
				if (isNaN(shareFixedNum) || shareFixedNum <= 0) {
					uni.showToast({
						title: '分享人固定金额必须大于0',
						icon: 'none'
					});
					return false;
				}
			}

			// 验证规格设置
			if (!this.specList || this.specList.length === 0) {
				uni.showToast({
					title: '请添加规格',
					icon: 'none'
				});
				return false;
			}

			// 验证规格名称和规格值
			for (const spec of this.specList) {
				if (!spec.name) {
					uni.showToast({
						title: '请输入规格名称',
						icon: 'none'
					});
					return false;
				}
				if (!spec.spec_list || spec.spec_list.length === 0) {
					uni.showToast({
						title: `请为规格"${spec.name}"添加规格值`,
						icon: 'none'
					});
					return false;
				}
				for (const value of spec.spec_list) {
					if (!value.value) {
						uni.showToast({
							title: `请输入规格"${spec.name}"的规格值`,
							icon: 'none'
						});
						return false;
					}
				}
			}

			// 验证价格设置
			if (!this.priceList || this.priceList.length === 0) {
				uni.showToast({
					title: '请设置套餐价格',
					icon: 'none'
				});
				return false;
			}

			for (const price of this.priceList) {
				if (!price.original_price) {
					uni.showToast({
						title: '请输入套餐原价',
						icon: 'none'
					});
					return false;
				}
				if (!price.price) {
					uni.showToast({
						title: '请输入套餐售价',
						icon: 'none'
					});
					return false;
				}
				const originalPrice = parseFloat(price.original_price);
				const salePrice = parseFloat(price.price);
				
				if (isNaN(originalPrice) || originalPrice <= 0) {
					uni.showToast({
						title: '套餐原价必须大于0',
						icon: 'none'
					});
					return false;
				}
				if (isNaN(salePrice) || salePrice <= 0) {
					uni.showToast({
						title: '套餐售价必须大于0',
						icon: 'none'
					});
					return false;
				}
				if (salePrice >= originalPrice) {
					uni.showToast({
						title: '套餐售价必须低于原价',
						icon: 'none'
					});
					return false;
				}
			}

			// 验证优惠券设置
			if (this.isCouponEnabled) {
				if (!this.couponAmount) {
					uni.showToast({
						title: '请输入优惠券金额',
						icon: 'none'
					});
					return false;
				}
				const couponAmountNum = parseFloat(this.couponAmount);
				if (isNaN(couponAmountNum) || couponAmountNum <= 0) {
					uni.showToast({
						title: '优惠券金额必须大于0',
						icon: 'none'
					});
					return false;
				}
			}

			return true;
		},
		// 添加规格项
		addSpecItem() {
			if (this.specList.length >= 3) {
				uni.showToast({
					title: '最多添加3个规格',
					icon: 'none'
				});
				return;
			}
			this.specList.push({
				id: '',
				name: '',
				spec_list: [
						{
								id: '',
								value: '',
								image: ''
						}
				]
			});
		},

		// 删除规格
		deleteSpec(index) {
			this.specList.splice(index, 1);
		},

		// 添加规格值
		addSpecValue(specIndex) {
			this.specList[specIndex].spec_list.push({
					id: '',
					value: '',
			})
		},

		// 删除规格值
		deleteValue(specIndex, valueIndex) {
			this.specList[specIndex].spec_list.splice(valueIndex, 1);
		},

		// 确认规格设置
		confirmSpecs() {
			// 这里添加验证逻辑
			if (!this.validateSpecs()) {
				return;
			}

			// 处理数据并关闭弹窗
			this.showPopup = false;
			// TODO: 处理确认后的数据
		},

		// 验证规格数据
		validateSpecs() {
			if (this.specList.length === 0) {
				uni.showToast({
					title: '请至少添加一个规格',
					icon: 'none'
				});
				return false;
			}
			// 添加其他验证逻辑
			return true;
		},
		formatSpecValues(str) {
			// 添加更严格的参数验证，避免undefined错误
			if (!str || typeof str !== 'string' || str.trim() === '') {
				return '';
			}
			return str.split(',').join(' + ');
		},
		// 上一步
		prevStep() {
			this.$emit('prev');
		},
		// 从缓存加载数据
		loadFromCache() {
			if (this.formCache && Object.keys(this.formCache).length > 0) {
				console.log('StepTwo从缓存恢复数据:', this.formCache);
				// 暂时禁用watch，避免循环触发
				this.isLoadingFromCache = true;
				
				// 恢复表单数据
				this.shareType = this.formCache.shareType || 1;
				this.shareRatio = this.formCache.shareRatio || '';
				this.shareFixed = this.formCache.shareFixed || '';
				this.implementType = this.formCache.implementType || 1;
				this.implementRatio = this.formCache.implementRatio || '';
				this.implementFixed = this.formCache.implementFixed || '';
				this.isCouponEnabled = this.formCache.isCouponEnabled || false;
				this.couponAmount = this.formCache.couponAmount || '';
				
				// 恢复复杂对象数据，进行深拷贝避免引用问题
				if (this.formCache.specList) {
					this.specList = JSON.parse(JSON.stringify(this.formCache.specList));
				}
				
				// 确保activitySpecs有正确的结构
				if (!this.activitySpecs) {
					this.activitySpecs = { spec_value_list: [] };
				}
				
				if (this.formCache.priceList && Array.isArray(this.formCache.priceList)) {
					this.priceList = JSON.parse(JSON.stringify(this.formCache.priceList));
					// 同时更新activitySpecs，但避免触发watch
					this.activitySpecs = {
						...this.activitySpecs,
						spec_value_list: JSON.parse(JSON.stringify(this.formCache.priceList))
					};
				} else {
					// 如果没有缓存数据，确保有默认值
					this.priceList = [];
					this.activitySpecs.spec_value_list = [];
				}
				
				// 重新启用watch
				this.$nextTick(() => {
					this.isLoadingFromCache = false;
				});
			} else {
				// 如果没有缓存，确保数据结构正确
				if (!this.activitySpecs) {
					this.activitySpecs = { spec_value_list: [] };
				}
			}
		},
		
		// 保存到缓存
		saveToCache() {
			try {
				const cacheData = {
					shareType: this.shareType,
					shareRatio: this.shareRatio,
					shareFixed: this.shareFixed,
					implementType: this.implementType,
					implementRatio: this.implementRatio,
					implementFixed: this.implementFixed,
					isCouponEnabled: this.isCouponEnabled,
					couponAmount: this.couponAmount,
					// 对复杂对象进行深拷贝，避免循环引用
					specList: JSON.parse(JSON.stringify(this.specList)),
					// 只保存priceList，不保存activitySpecs以避免循环引用
					priceList: JSON.parse(JSON.stringify(this.priceList))
				};
				
				this.$emit('updateCache', cacheData);
				console.log('StepTwo保存数据到缓存成功');
			} catch (error) {
				console.error('StepTwo保存缓存失败:', error);
				
				// 如果出现错误，保存简化版本
				const simplifiedData = {
					shareType: this.shareType,
					shareRatio: this.shareRatio,
					shareFixed: this.shareFixed,
					implementType: this.implementType,
					implementRatio: this.implementRatio,
					implementFixed: this.implementFixed,
					isCouponEnabled: this.isCouponEnabled,
					couponAmount: this.couponAmount
				};
				
				this.$emit('updateCache', simplifiedData);
				console.log('StepTwo保存简化版缓存成功');
			}
		}
	},
	created() {
		// 确保数据结构在组件创建时就正确初始化
		if (!this.activitySpecs) {
			this.activitySpecs = { spec_value_list: [] };
		}
		if (!this.activitySpecs.spec_value_list) {
			this.activitySpecs.spec_value_list = [];
		}
	},
	mounted() {
		this.trainerList();
		// 从缓存恢复数据
		this.loadFromCache();
	},
	beforeDestroy() {
		clearTimeout(this.debounceTimer);
	}
};
</script>

<style lang="scss" scoped>
.step-item {
	background-color: #ffffff;
	border-radius: 8rpx;
	padding: 20rpx;
}

/* 步骤头部样式 */
.step-header {
	text-align: center;
	margin-bottom: 30rpx;
	padding-bottom: 20rpx;
	border-bottom: 1rpx solid #d5d5d5;
}

.step-icon {
	font-size: 48rpx;
	margin-bottom: 12rpx;
}

.step-title-main {
	font-size: 32rpx;
	font-weight: 500;
	color: #000000;
	margin-bottom: 8rpx;
}

.step-description {
	font-size: 24rpx;
	color: #666;
	line-height: 1.4;
}

.activity-title {
	display: flex;
	flex-direction: column;
	margin: 20rpx 0;
	padding: 20rpx;
	background: #f8f9fa;
	border-radius: 8rpx;

	.title-text {
		font-size: 28rpx;
		font-weight: 500;
		color: #000000;
		margin-bottom: 8rpx;
	}
	
	.fee-note {
		font-size: 22rpx;
		color: #999;
	}
}

.section {
	background: #ffffff;
	border-radius: 8rpx;
	padding: 20rpx;
	margin-bottom: 16rpx;
	border: 1rpx solid #d5d5d5;

	.section-title {
		font-size: 28rpx;
		font-weight: 500;
		color: #000000;
		margin-bottom: 20rpx;
		padding-bottom: 12rpx;
		border-bottom: 1rpx solid #d5d5d5;
	}
}

.package-list {
	margin-bottom: 20rpx;

	.package-item {
		background: #f8f9fa;
		border-radius: 8rpx;
		padding: 16rpx;
		margin-bottom: 12rpx;
		border: 1rpx solid #e9ecef;

		.package-content {
			.requirement {
				font-size: 26rpx;
				color: #333;
				margin-bottom: 8rpx;
				display: block;
			}

			.price-info {
				display: flex;
				align-items: center;
				gap: 12rpx;

				.original-price {
					font-size: 24rpx;
					color: #999;
					text-decoration: line-through;
				}

				.current-price {
					font-size: 26rpx;
					color: #0dc160;
					font-weight: 500;
				}

				.discount {
					font-size: 22rpx;
					color: #ff6b35;
				}
			}
		}
	}

	.empty-tips {
		text-align: center;
		color: #999;
		font-size: 24rpx;
		padding: 40rpx 0;
	}
}

.add-package {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 16rpx;
	border: 2rpx dashed #0dc160;
	border-radius: 8rpx;
	color: #0dc160;
	font-size: 26rpx;

	text {
		margin-left: 8rpx;
	}
}

.profit-settings {
	.setting-group {
		margin-bottom: 24rpx;

		.sub-title {
			font-size: 26rpx;
			color: #333;
			margin-bottom: 12rpx;
			font-weight: 500;
		}

		.radio-group {
			margin-bottom: 16rpx;

			.radio-item {
				display: inline-flex;
				align-items: center;
				margin-right: 40rpx;
				font-size: 24rpx;
				color: #666;

				radio {
					margin-right: 8rpx;
				}
			}
		}

		.input-group {
			display: flex;
			align-items: center;
			gap: 12rpx;

			input {
				flex: 1;
				height: 70rpx;
				border: 1rpx solid #dcdfe6;
				border-radius: 4px;
				padding: 0 16rpx;
				font-size: 26rpx;
			}

			.unit {
				font-size: 24rpx;
				color: #666;
				min-width: 40rpx;
			}
		}
	}
}

.income-result {
	padding: 16rpx;
	background: #f0fff4;
	border-radius: 8rpx;
	border: 1rpx solid #c8e6c9;

	text {
		color: #0dc160;
		font-size: 26rpx;
		font-weight: 500;
	}
}

.income-tips {
	padding: 16rpx;
	color: #999;
	font-size: 24rpx;
	text-align: center;
}

.loading-wrapper {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 16rpx;
	
	.loading-text {
		margin-left: 12rpx;
		color: #666;
		font-size: 24rpx;
	}
}

.coupon-settings {
	.coupon-item {
		display: flex;
		align-items: center;
		margin-bottom: 16rpx;

		&:first-child {
			margin-bottom: 20rpx;
		}

		input {
			flex: 1;
			height: 70rpx;
			border: 1rpx solid #dcdfe6;
			border-radius: 4px;
			padding: 0 16rpx;
			font-size: 26rpx;
			margin-right: 12rpx;

			&:disabled {
				background: #f5f5f5;
				color: #ccc;
			}
		}

		.unit {
			font-size: 24rpx;
			color: #666;
			min-width: 40rpx;
		}

		/deep/ .u-checkbox {
			font-size: 26rpx;
		}
	}
}

/* 底部按钮样式 */
.bottom-buttons {
	display: flex;
	justify-content: center;
	gap: 24rpx;
	padding: 40rpx 20rpx;
	margin-top: 20rpx;

	.cancel-btn {
		width: 331rpx;
		height: 90rpx;
		background: #fcfffe;
		border-radius: 44rpx;
		border: 2rpx solid #d5d5d5;
		display: flex;
		align-items: center;
		justify-content: center;

		text {
			font-size: 32rpx;
			color: #333;
		}
	}

	.save-btn {
		width: 331rpx;
		height: 90rpx;
		background: #0dc160;
		border-radius: 44rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		text {
			font-size: 32rpx;
			color: #ffffff;
		}
	}
}

/* 弹窗样式优化 */
.popup-container {
	background: #ffffff;
	border-radius: 16rpx 16rpx 0 0;
	max-height: 80vh;
	overflow: hidden;
}

.popup-header {
	padding: 24rpx;
	border-bottom: 1rpx solid #d5d5d5;
	text-align: center;

	.popup-title {
		font-size: 30rpx;
		color: #000000;
		font-weight: 500;
	}
}

.popup-content {
	padding: 24rpx;
	max-height: 60vh;
	overflow-y: auto;
}

.spec-section,
.price-section {
	margin-bottom: 24rpx;

	.section-header {
		display: flex;
		align-items: center;
		margin-bottom: 16rpx;
		font-size: 26rpx;
		color: #333;
		font-weight: 500;

		.limit-text {
			font-size: 22rpx;
			color: #999;
			margin-left: 8rpx;
		}

		.add-spec {
			margin-left: auto;
			color: #0dc160;
			font-size: 24rpx;
		}
	}
}

.spec-list {
	.spec-item {
		margin-bottom: 24rpx;
		padding: 16rpx;
		background: #f8f9fa;
		border-radius: 8rpx;
		border: 1rpx solid #e9ecef;
		
		.spec-name-section {
			margin-bottom: 16rpx;
			
			.spec-name-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 12rpx;
				
				text {
					font-size: 24rpx;
					color: #333;
					font-weight: 500;
				}
			}
			
			.spec-name-input {
				width: 100%;
				height: 60rpx;
				border: 1rpx solid #dcdfe6;
				border-radius: 4px;
				padding: 0 16rpx;
				font-size: 24rpx;
				box-sizing: border-box;
			}
		}
		
		.spec-values-section {
			.spec-values-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 12rpx;
				
				text {
					font-size: 24rpx;
					color: #333;
					font-weight: 500;
				}
				
				.add-value {
					color: #0dc160;
					font-size: 22rpx;
				}
			}
			
			.value-list {
				display: flex;
				flex-direction: column;
				gap: 12rpx;
				
				.value-item {
					display: flex;
					align-items: center;
					gap: 8rpx;
					
					input {
						flex: 1;
						height: 60rpx;
						border: 1rpx solid #dcdfe6;
						border-radius: 4px;
						padding: 0 16rpx;
						font-size: 24rpx;
						box-sizing: border-box;
					}
					
					image {
						flex-shrink: 0;
					}
				}
			}
		}
	}
}

.price-table {
	border: 1rpx solid #dcdfe6;
	border-radius: 8rpx;
	overflow: hidden;

	.table-header {
		display: grid;
		grid-template-columns: 2fr 1fr 1fr;
		background-color: #f8f9fa;
		padding: 16rpx;
		text-align: center;
		font-size: 24rpx;
		color: #333;
		font-weight: 500;
	}

	.table-row {
		display: grid;
		grid-template-columns: 2fr 1fr 1fr;
		padding: 16rpx;
		border-top: 1rpx solid #dcdfe6;
		align-items: center;

		.spec-name {
			font-size: 22rpx;
			color: #666;
		}

		input {
			height: 50rpx;
			border: 1rpx solid #dcdfe6;
			border-radius: 4px;
			padding: 0 12rpx;
			text-align: center;
			font-size: 22rpx;
		}
	}
}

.popup-footer {
	padding: 16rpx 24rpx;
	border-top: 1rpx solid #d5d5d5;

	.confirm-btn {
		width: 100%;
		height: 80rpx;
		background: #0dc160;
		color: #fff;
		border-radius: 40rpx;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border: none;
	}
}
</style>
